package com.quarkus.resource;

import com.quarkus.model.Fruit;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *  使用Rest api 实现访问
 */
@Path("fruit")
@Produces(MediaType.APPLICATION_JSON)
public class FruitResource {

    @Inject
    RestClient restClient;

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public JsonObject add(Fruit fruit) throws IOException {

        var request = new Request("POST", "/fruit/_doc/"+ fruit.id);

        request.setJsonEntity(JsonObject.mapFrom(fruit).toString());

        return new JsonObject(EntityUtils.toString(restClient.performRequest(request).getEntity()));
    }

    @GET
    @Path("{id}")
    public Fruit fruit(@PathParam("id") String id) throws IOException {
        var request = new Request("GET", "fruit/_doc/"+id);

        Response response = restClient.performRequest(request);

        return new JsonObject(EntityUtils.toString(response.getEntity())).getJsonObject("_source").mapTo(Fruit.class);
    }

    @GET
    @Path("query/color/{color}")
    public List<Fruit> searchByColor(@PathParam("color") String color) throws IOException {
        return search("color", color);
    }

    @GET
    @Path("query/name/{name}")
    public List<Fruit> searchByName(@PathParam("name") String name) throws IOException {
        return search("name", name);
    }

    private List<Fruit> search(String term, String match) throws IOException {
        Request request = new Request(
                "GET",
                "/fruit/_search");
        //construct a JSON query like {"query": {"match": {"<term>": "<match"}}
        JsonObject termJson = new JsonObject().put(term, match);
        JsonObject matchJson = new JsonObject().put("match", termJson);
        JsonObject queryJson = new JsonObject().put("query", matchJson);
        request.setJsonEntity(queryJson.encode());
        Response response = restClient.performRequest(request);
        String responseBody = EntityUtils.toString(response.getEntity());

        JsonObject json = new JsonObject(responseBody);
        JsonArray hits = json.getJsonObject("hits").getJsonArray("hits");
        List<Fruit> results = new ArrayList<>(hits.size());
        for (int i = 0; i < hits.size(); i++) {
            JsonObject hit = hits.getJsonObject(i);
            Fruit fruit = hit.getJsonObject("_source").mapTo(Fruit.class);
            results.add(fruit);
        }
        return results;
    }


}
